package com.xiaozhen.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.blog.entity.Blog;
import com.xiaozhen.blog.entity.Type;
import com.xiaozhen.blog.service.BlogService;
import com.xiaozhen.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @create 2023-04-22 13:14
 * 分类页面
 */
@Controller
@RequestMapping("/types")
public class TypeController {
    @Autowired
    private TypeService typeService;

    @GetMapping("/{id}")
    public String types(@RequestParam(value = "page", required = false) Long page,
                        @PathVariable Long id,
                        Model model) {
        // 查询所有分类
        List<Type> typeList = typeService.typeList();
        // 若传过来的 id 为 -1，那么默认选择第一个分类
        if (id == -1) {
            id = typeList.get(0).getId();
        }
        // 如果没有传入参数，那么我们把page定义为第 1 页
        if (page == null) {
            page = 1L;
        }
        // 创建对象，传递分页相关参数，每页记录数为 6
        Page<Blog> pageParam = new Page<>(page, 6);

        // 将数据返回给前端
        model.addAttribute("types", typeList);
        model.addAttribute("activeTypeId", id);
        model.addAttribute("page", typeService.blogPage(pageParam,id));
        return "types";
    }
}
